package de.g18.it0a.jlaser.factory;

import de.g18.it0a.jlaser.domain.Laser;
import de.g18.it0a.jlaser.domain.LaserConfiguration;
import de.g18.it0a.jlaser.domain.Mirror;
import de.g18.it0a.jlaser.domain.Position;
import de.g18.it0a.jlaser.domain.Room;
import de.g18.it0a.jlaser.domain.RoomConfiguration;
import de.g18.it0a.jlaser.domain.Vetrine;
import de.g18.it0a.jlaser.exception.IllegalPositionException;
import de.g18.it0a.jlaser.exception.MalformedConfigurationException;


public class RoomFactory {


    private RoomFactory() {
        // prevent instantiation
    }

    public static final Room buildRoom(RoomConfiguration aRoomConfig) throws MalformedConfigurationException {
        return buildRoom(aRoomConfig, LaserConfiguration.EMPTY);
    }

    public static final Room buildRoom(RoomConfiguration aRoomConfig, LaserConfiguration aLaserConfig) throws MalformedConfigurationException {
        Room room = new Room(aRoomConfig);

        try {
            room.addFixture(new Laser(aRoomConfig.getLaserPosition()));
            for (Position position : aRoomConfig.getVetrinePositions()) {
                room.addFixture(new Vetrine(position));
            }
        } catch (IllegalPositionException e) {
            throw new MalformedConfigurationException(aRoomConfig, e);
        }
        addMirrors(room, aLaserConfig);
        return room;
    }

    private static void addMirrors(Room aRoom, LaserConfiguration aLaserConfig) {
        Laser laser = aRoom.getLaser();
        laser.setPointedPosition(aLaserConfig.getMirrors().size() == 0 ? aLaserConfig.getEnd()
                                                                       : aLaserConfig.getMirrors().firstElement().getPosition());
        for (Mirror mirror : aLaserConfig.getMirrors()) {
            try {
                aRoom.addFixture(mirror);
            } catch (IllegalPositionException e) {
                throw new IllegalStateException("SolutionManager got invalid data to work with!", e);
            }
        }
    }
}
